import { defHttp } from '/@/utils/http/axios';
import { downloadFileUrl, removeFileUrl, fileListUrl } from '/@/api/common/api';
import { ContentTypeEnum } from '/@/enums/httpEnum';

export function useFile(emit: any, type: string) {
  function getFileItemOfRes(info: any) {
    const downloadPath = `${downloadFileUrl}?fileKey=${info.fileKey}&fileName=${info.fileName}`;
    const removePath = `${removeFileUrl}?fileKey=${info.fileKey}`;
    const url = info.url;
    const newInfo: any = {
      file_id: info.fileKey,
      file_name: info.fileName,
      file_path: url,
      online_view_url: url,
      download_url: downloadPath,
      del_file_url: removePath,
      file_size: info.size,
      // create_time: res.timestamp,
      support_online_view: true,
    };
    if (type === 'image') {
      newInfo.origin_url = url;
      newInfo.thumb_url = url;
    }
    return newInfo;
  }
  function formatUploadData(res: any) {
    const info = res.result;
    const newInfo = getFileItemOfRes(info);
    res.data = [newInfo];
    return res;
  }

  function emitValue(value: any[]) {
    emit('change', value);
    emit('update:value', value);
  }

  function handleUpdate(data: any) {
    const fileIds: string[] = [];
    data.fileLists.forEach((item: any) => {
      if (item?.response?.data) {
        const id = item.response?.data?.[0]?.file_id;
        if (id) {
          fileIds.push(id);
        }
      }
    });
    emitValue(fileIds);
  }

  function customRemovePromise(file: any) {
    const url = file?.response?.data?.[0]?.del_file_url;
    if (url) {
      return defHttp.get({ url }, { isTransformResponse: false });
    }
  }

  async function customDisplayList(ids: string[]) {
    if (!ids || ids.length === 0) {
      return;
    }
    const dir = getDirFromId(ids[0]);
    const res = await defHttp.post(
      { url: fileListUrl, headers: { 'Content-type': ContentTypeEnum.FORM_URLENCODED }, data: { dir } },
      { isTransformResponse: false }
    );
    if (res.code == 200) {
      const list = res.result.filter((item) => {
        const fileKey = item.fileKey;
        if (ids.includes(fileKey)) {
          return true;
        }
      });

      const newList = list.map((item) => {
        const newInfo = getFileItemOfRes(item);
        return newInfo;
      });

      return {
        code: '000000',
        data: newList,
      };
    }
  }

  function getDirFromId(id: string) {
    const dirs = id.split('/');
    return dirs[0];
  }

  function generateDir() {
    let id = s4() + new Date().getTime().toString();
    return id;
  }
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return {
    formatUploadData,
    handleUpdate,
    customRemovePromise,
    customDisplayList,
    generateDir,
  };
}
